package com.dmp.onlinestore.model.service.impl;

import java.util.List;
import com.dmp.onlinestore.model.dao.ProductDao;
import com.dmp.onlinestore.model.dao.base.DaoException;
import com.dmp.onlinestore.model.dao.base.DaoFactory;
import com.dmp.onlinestore.model.dao.base.DaoTransaction;
import com.dmp.onlinestore.model.dto.ProductBean;
import com.dmp.onlinestore.model.dto.ProductBeanFilterSpec;
import com.dmp.onlinestore.model.service.Catalog;
import com.dmp.onlinestore.model.service.ProductBeanPager;
import com.dmp.onlinestore.model.service.base.ServiceExecutionException;
import com.dmp.onlinestore.model.service.base.ServiceFactory;

public class CatalogImpl implements Catalog {

	public CatalogImpl () {
	}
		
	public ProductBeanPager getProducts() throws ServiceExecutionException {
		// Default filter means "match anything".
		return getProducts(ProductBeanFilterSpec.getDefaultFilter());
	}
	
	public ProductBeanPager getProducts(ProductBeanFilterSpec filter) throws ServiceExecutionException {
		try {
			DaoTransaction transaction = DaoFactory.instance().getDaoTransaction();
			ProductDao dao = DaoFactory.instance().getProductDao(transaction);
			List<ProductBean> productList = dao.getProducts(filter);
			transaction.finish();
			ProductBeanPager pager = ServiceFactory.instance().getProductBeanPager(productList);
			return pager;
		}
		catch (DaoException e) {
			System.out.println("Dao exception: \"" + e.getErrorString() + "\"");
			e.printStackTrace();
			throw new ServiceExecutionException("Error executing service (accessing persistent store)");
		}
	}

}
